<template>
	<view class="list-department">
		<view class="crumbs">
			<scroll-view :scroll-x="true">
				<view class="item" v-for="(v, k) in crumbs" :key="k" @click="crumbsClick(v, k)">
					<u-icon v-if="k > 0" name="arrow-right" color="#999" />
					<text>{{ v.text }}</text>
				</view>
			</scroll-view>
		</view>
		<uni-list>
			<u-checkbox-group @change="checkboxChange">
				<uni-list-item v-for="(v, k) in curList" :key="k">
					<view slot="header" class="hd">
						<u-checkbox v-model="v.checked" :name="v.id">{{ v.name }}</u-checkbox>
					</view>

					<u-icon v-if="v.children" name="arrow-right" slot="footer" color="#999" @click="toggleList(v, k)"></u-icon>
				</uni-list-item>
			</u-checkbox-group>
		</uni-list>
	</view>
</template>

<script>
export default {
	props: {},
	data: () => ({
		// 所有列表
		list: [],
		// 当前列表
		curList: [],
		// 面包屑
		crumbs: [{ text: '全部', list: [] }],
		// 所选择的所有的值
		checks: [],
	}),
	methods: {
		// 获取部门
		async getData() {
			let res = await this.$api.customer.common.department({ type: 'tree' });
			if (res.code === 200) {
				this.list = res.data || [];
				// 初始化面包屑
				this.crumbsClick({}, 0);
			}
		},
		// 面包屑点击事件
		crumbsClick(row, index) {
			if (index === 0) {
				this.curList = this.list;
				this.crumbs = [{ text: '全部', list: this.list }];
			} else {
				this.curList = row.list;
				this.crumbs.splice(index + 1, this.curList.length);
			}
		},
		// 切换列表数据
		toggleList(row, index) {
			this.curList = row.children;
			this.crumbs.push({ text: row.name, list: row.children });
		},
		// 复选框触发选择事件
		checkboxChange() {
			this.checks = [];
			// 因为list和crubms是引用关系，所以list里面也会有checked字段
			this.filterCheckIds(this.list);
			this.$emit('selected', this.checks.length, this.checks.join(','));
		},
		// 简单递归筛选出选中的部门id
		filterCheckIds(list) {
			list.forEach((v) => {
				if (v.checked) {
					this.checks.push(v.id);
				}
				if (v.children) {
					this.filterCheckIds(v.children);
				}
			});
		},
	},
	computed: {},
	watch: {},

	// 组件周期函数--监听组件挂载完毕
	mounted() {
		this.getData();
	},
	// 组件周期函数--监听组件数据更新之前
	beforeUpdate() {},
	// 组件周期函数--监听组件数据更新之后
	updated() {},
	// 组件周期函数--监听组件激活(显示)
	activated() {},
	// 组件周期函数--监听组件停用(隐藏)
	deactivated() {},
	// 组件周期函数--监听组件销毁之前
	beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
.crumbs {
	margin: 0 15px;
	/deep/ .uni-scroll-view-content {
		white-space: nowrap;
		padding: 15px 0;

		.item {
			display: inline-block;
			.u-icon {
				margin: 0 5px;
			}
		}
	}
}
.u-checkbox-group {
	display: block;
	flex-wrap: nowrap;
}
</style>
